# -*- coding: utf-8 -*-
from common.config import *
from db.mysql import MysqlClient
from common.helper import Helper
import aiohttp, asyncio
from itertools import product
from urllib.parse import urlencode
import json

class Spider(object):
    def __init__(self):
        self.name = "境外旅游保险"
        self.mysql = MysqlClient()

    def genProductInfo(self):
        plan = {
            "days": ["7d", "15d", "30d", "50d"],
            "people_count": [str(i) for i in range(1, 11)],
            "accident_death":["100000"],
            "accident_medical":["10000"],
            "acute_death":["50000"],
            "family_property":["20000"]
        }
        for v in product( plan["days"],plan["people_count"],plan["accident_death"],plan["accident_medical"],plan["acute_death"],plan["family_property"]):
            data = Helper.formatProductInfo( plan,v )
            yield data
    #执行爬虫
    async def requestJson(self,dt):
        data = self.filterPayload( dt )
        payload = urlencode( data ).replace("+","")
        async with aiohttp.ClientSession() as session:
            async with session.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload) as resp:
                res = await resp.text()
                if "totalPrice" in res:
                    price = Helper.decimalParse( json.loads( res )["totalPrice"] )
                    print( dt )
                    data = {
                        "name":self.name,
                        "company":"北部湾财产保险",
                        "price":price
                    }
                    data.update( dt )
                    Helper.mergeTable( self.name,self.mysql,data )
    #filterPayload
    def filterPayload(self,data=None):
        params = '''
        insuranceid_25419_保险金额: 100000
        insuranceid_25420_保险金额: 10000
        insuranceid_25421_保险金额: 50000
        insuranceid_25422_保险金额: 20000
        suiteId: 5761
        period: 30
        amount: 
        personCount: 3
        backInsuranceCount: 
        trafficAccident: abroadTravel
        '''
        payload = Helper.perfectJson( params )
        payload["period"] = data["days"].replace("d","")
        payload["personCount"] = data["people_count"]
        return payload

    def asyncTask(self):

        tasks = [self.requestJson( data ) for data in self.genProductInfo() ]
        event_loop = asyncio.get_event_loop()
        event_loop.run_until_complete( asyncio.gather( *tasks ))
        event_loop.close()

if __name__ == '__main__':
    s = Spider()
    s.asyncTask()
